// 更新时间
function updateDateTime() {
    const now = new Date();
    const options = {
        year: 'numeric', month: 'long', day: 'numeric',
        hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
    };
    document.getElementById('currentDateTime').textContent = now.toLocaleDateString('zh-CN', options);
}
setInterval(updateDateTime, 1000);
updateDateTime();

/* ========== 统一颜色池 ========== */
const colorPool = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de'];

//* ====== 业务类型分布饼图 ====== */
function initBusinessTypeChart() {
    const chart = echarts.init(document.getElementById('businessTypeChart'));
    chart.setOption({
        tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
        legend: { orient: 'vertical', right: 10, top: 'center', textStyle: { color: '#a0a0a0' } },
        series: [{ name: '业务类型', type: 'pie', radius: ['40%', '70%'], data: [], label: { color: '#a0a0a0' } }]
    });

    fetch('/api/indicators/businessType')
        .then(res => res.json())
        .then(arr => {
            const data = arr.map((item, idx) => ({
                name: item.business_type || item.businessType,
                value: item.package_quantity || item.packageQuantity,
                itemStyle: { color: colorPool[idx % colorPool.length] }
            }));
            chart.setOption({ series: [{ data }] });
        })
        .catch(err => console.error('业务类型数据加载失败:', err));
    return chart;
}

/* ========== 2. 城市派件量横向柱图 ========== */
function initCityDeliveryChart() {
    const chart = echarts.init(document.getElementById('cityDeliveryChart'));
    chart.setOption({
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        grid: { left: '3%', right: '4%', bottom: '3%', top: '10%', containLabel: true },
        xAxis: { type: 'value', axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' }, splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } } },
        yAxis: { type: 'category', data: [], axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' } },
        series: [{ name: '派件量', type: 'bar', data: [], itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{ offset: 0, color: '#83bff6' }, { offset: 1, color: '#188df0' }]) } }]
    });

    fetch('/api/indicators/cityDelivery')
        .then(res => res.json())
        .then(arr => {
            const cities = arr.map(item => item.city);
            const values = arr.map(item => item.delivery_quantity || item.deliveryQuantity);
            chart.setOption({ yAxis: { data: cities }, series: [{ data: values }] });
        })
        .catch(err => console.error('城市派件量数据加载失败:', err));
    return chart;
}

/* ========== 3. 客户行为双轴图 ========== */
function initCustomerBehaviorChart() {
    const chart = echarts.init(document.getElementById('customerBehaviorChart'));
    chart.setOption({
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        legend: { data: ['寄递频次', '平均消费金额'], textStyle: { color: '#a0a0a0' }, top: 10 },
        grid: { left: '3%', right: '4%', bottom: '3%', top: '20%', containLabel: true },
        xAxis: { type: 'category', data: [], axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' } },
        yAxis: [
            { type: 'value', name: '寄递频次', axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' }, splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } } },
            { type: 'value', name: '平均消费金额', axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' }, splitLine: { show: false } }
        ],
        series: [
            { name: '寄递频次', type: 'bar', data: [], itemStyle: { color: '#5470c6' } },
            { name: '平均消费金额', type: 'line', yAxisIndex: 1, data: [], lineStyle: { color: '#91cc75' }, symbol: 'circle', symbolSize: 6 }
        ]
    });

    fetch('/api/indicators/customerBehavior')
        .then(res => res.json())
        .then(arr => {
            // 按客户ID分组或按服务类型分组
            const categories = arr.map(item => item.frequently_used_service_type || item.frequentlyUsedServiceType || `客户${item.customer_id || item.customerId}`);
            const frequencies = arr.map(item => parseFloat(item.shipping_frequency || item.shippingFrequency || 0));
            const amounts = arr.map(item => parseFloat(item.average_spending_amount || item.averageSpendingAmount || 0));
            chart.setOption({ 
                xAxis: { data: categories }, 
                series: [{ data: frequencies }, { data: amounts }] 
            });
        })
        .catch(err => console.error('客户行为数据加载失败:', err));
    return chart;
}

/* ========== 4. KPI 卡片 ========== */
function loadKPI() {
    fetch('/api/indicators/incomeExpense')
        .then(res => res.json())
        .then(data => {
            // 今日包裹总量 - 需要从其他接口获取或计算
            // 暂时使用默认值，如果后端有提供该字段则使用
            const todayPkg = data.today_package_count || data.todayPackageCount || 0;
            const income = parseFloat(data.income_amount || data.incomeAmount || 0);
            const expense = parseFloat(data.expense_amount || data.expenseAmount || 0);
            const netIncome = parseFloat(data.net_income || data.netIncome || 0);
            
            document.getElementById('kpi-today-pkg').textContent = todayPkg.toLocaleString();
            document.getElementById('kpi-income').textContent = '¥' + income.toLocaleString();
            document.getElementById('kpi-expense').textContent = '¥' + expense.toLocaleString();
            document.getElementById('kpi-net').textContent = '¥' + netIncome.toLocaleString();
        })
        .catch(err => {
            console.error('KPI数据加载失败:', err);
            // 失败时显示默认值
            document.getElementById('kpi-today-pkg').textContent = '0';
            document.getElementById('kpi-income').textContent = '¥0';
            document.getElementById('kpi-expense').textContent = '¥0';
            document.getElementById('kpi-net').textContent = '¥0';
        });
}

/* ========== 5. 网点运营表格 ========== */
function loadOutletTable() {
    fetch('/api/indicators/outletOperation')
        .then(res => res.json())
        .then(arr => {
            const tbody = document.querySelector('.table-container tbody');
            tbody.innerHTML = arr.slice(0, 5).map((item, idx) => `
                <tr>
                    <td>${idx + 1}</td>
                    <td>网点${item.outlet_id || item.outletId}</td>
                    <td>${(item.daily_package_processing || item.dailyPackageProcessing || 0).toLocaleString()}</td>
                    <td>${parseFloat(item.customer_satisfaction || item.customerSatisfaction || 0).toFixed(2)}</td>
                    <td>${(parseFloat(item.exception_handling_timeliness_ra || item.exceptionHandlingTimelinessRa || 0) * 100).toFixed(1)}%</td>
                </tr>
            `).join('');
        })
        .catch(err => {
            console.error('网点运营数据加载失败:', err);
            // 保持HTML中的默认数据
        });
}

/* ========== 6. 包裹处理状态趋势图 ========== */
function initPackageStatusChart() {
    const chart = echarts.init(document.getElementById('packageStatusChart'));
    const statusMap = {
        '待揽收': 'inbound_quantity',
        '运输中': 'in_stock_quantity',
        '派送中': 'outbound_quantity',
        '已签收': 'returned_signed_quantity',
        '异常': 'lost_quantity'
    };
    const legend = Object.keys(statusMap);
    
    chart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: legend, textStyle: { color: '#a0a0a0' }, top: 10 },
        grid: { left: '3%', right: '4%', bottom: '3%', top: '20%', containLabel: true },
        xAxis: { type: 'category', boundaryGap: false, data: [], axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' } },
        yAxis: { type: 'value', axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' }, splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } } },
        series: legend.map((name, idx) => ({
            name,
            type: 'line',
            stack: '总量',
            areaStyle: { opacity: 0.3 },
            lineStyle: { width: 2 },
            data: [],
            color: colorPool[idx]
        }))
    });

    fetch('/api/indicators/packageProcessingStatus')
        .then(res => res.json())
        .then(arr => {
            // 按时间分组
            const timeMap = new Map();
            arr.forEach(item => {
                const time = item.statistics_time || item.statisticsTime;
                const timeStr = time ? new Date(time).toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' }) : '';
                if (!timeMap.has(timeStr)) {
                    timeMap.set(timeStr, item);
                }
            });
            
            const times = Array.from(timeMap.keys()).slice(0, 7);
            const series = legend.map((name, idx) => {
                const fieldName = statusMap[name];
                const camelFieldName = fieldName.replace(/_([a-z])/g, (m, p1) => p1.toUpperCase());
                return {
                    data: times.map(t => {
                        const item = timeMap.get(t);
                        return item ? (item[fieldName] || item[camelFieldName] || 0) : 0;
                    })
                };
            });
            
            chart.setOption({ xAxis: { data: times }, series });
        })
        .catch(err => console.error('包裹处理状态数据加载失败:', err));
    return chart;
}

/* ========== 7. 运输效率雷达图 ========== */
function initTransportEfficiencyChart() {
    const chart = echarts.init(document.getElementById('transportEfficiencyChart'));
    chart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: [], textStyle: { color: '#a0a0a0' }, top: 10 },
        radar: {
            indicator: [
                { name: '准时率', max: 100 },
                { name: '完成率', max: 100 },
                { name: '装载率', max: 100 },
                { name: '成本控制', max: 100 },
                { name: '燃油效率', max: 100 }
            ],
            splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } },
            axisLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } },
            splitArea: { show: false }
        },
        series: [{ name: '运输工具效率', type: 'radar', data: [] }]
    });

    fetch('/api/indicators/transportationEfficiency')
        .then(res => res.json())
        .then(arr => {
            const legends = arr.map(item => item.transport_mode || item.transportMode);
            const data = arr.map((item, idx) => {
                // 计算各项指标
                const onTimeRate = parseFloat(item.on_time_rate || item.onTimeRate || 0);
                const plannedTrips = parseFloat(item.planned_transport_trips || item.plannedTransportTrips || 1);
                const actualTrips = parseFloat(item.actual_completed_trips || item.actualCompletedTrips || 0);
                const completionRate = plannedTrips > 0 ? (actualTrips / plannedTrips * 100) : 0;
                
                // 其他指标需要根据实际数据计算，这里使用模拟值
                const loadRate = 85 + Math.random() * 10;
                const costControl = 80 + Math.random() * 15;
                const fuelEfficiency = 75 + Math.random() * 15;
                
                return {
                    name: item.transport_mode || item.transportMode,
                    value: [onTimeRate, completionRate, loadRate, costControl, fuelEfficiency],
                    areaStyle: { opacity: 0.3 },
                    lineStyle: { width: 2, color: colorPool[idx % colorPool.length] },
                    itemStyle: { color: colorPool[idx % colorPool.length] }
                };
            });
            
            chart.setOption({ 
                legend: { data: legends },
                series: [{ data }] 
            });
        })
        .catch(err => console.error('运输效率数据加载失败:', err));
    return chart;
}

/* ========== 8. 仓储运营柱折混合 ========== */
function initWarehouseOperationChart() {
    const chart = echarts.init(document.getElementById('warehouseOperationChart'));
    chart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: ['入库总量', '出库总量', '库存周转率'], textStyle: { color: '#a0a0a0' }, top: 10 },
        grid: { left: '3%', right: '4%', bottom: '3%', top: '20%', containLabel: true },
        xAxis: { type: 'category', data: [], axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' } },
        yAxis: [
            { type: 'value', name: '数量', axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' }, splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } } },
            { type: 'value', name: '周转率', axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' }, splitLine: { show: false } }
        ],
        series: [
            { name: '入库总量', type: 'bar', data: [], itemStyle: { color: '#5470c6' } },
            { name: '出库总量', type: 'bar', data: [], itemStyle: { color: '#91cc75' } },
            { name: '库存周转率', type: 'line', yAxisIndex: 1, data: [], lineStyle: { color: '#ee6666' }, symbol: 'circle', symbolSize: 6 }
        ]
    });

    fetch('/api/indicators/warehouseOperation')
        .then(res => res.json())
        .then(arr => {
            // 按日期排序并格式化
            const sortedData = arr.sort((a, b) => {
                const dateA = new Date(a.statistics_date || a.statisticsDate);
                const dateB = new Date(b.statistics_date || b.statisticsDate);
                return dateA - dateB;
            });
            
            const dates = sortedData.map(item => {
                const date = new Date(item.statistics_date || item.statisticsDate);
                return `${date.getMonth() + 1}月`;
            });
            const inbound = sortedData.map(item => item.total_inbound || item.totalInbound || 0);
            const outbound = sortedData.map(item => item.total_outbound || item.totalOutbound || 0);
            const turnover = sortedData.map(item => parseFloat(item.inventory_turnover_rate || item.inventoryTurnoverRate || 0));
            
            chart.setOption({ 
                xAxis: { data: dates }, 
                series: [{ data: inbound }, { data: outbound }, { data: turnover }] 
            });
        })
        .catch(err => console.error('仓储运营数据加载失败:', err));
    return chart;
}

/* ========== 9. 客户满意度面积图 ========== */
function initCustomerSatisfactionChart() {
    const chart = echarts.init(document.getElementById('customerSatisfactionChart'));
    chart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: ['满意度评分'], textStyle: { color: '#a0a0a0' }, top: 10 },
        grid: { left: '3%', right: '4%', bottom: '3%', top: '20%', containLabel: true },
        xAxis: { type: 'category', data: [], axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' } },
        yAxis: { type: 'value', min: 4, max: 5, axisLine: { lineStyle: { color: '#a0a0a0' } }, axisLabel: { color: '#a0a0a0' }, splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } } },
        series: [{
            name: '满意度评分',
            type: 'line',
            data: [],
            lineStyle: { color: '#91cc75', width: 2 },
            areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: 'rgba(145, 204, 117, 0.3)' }, { offset: 1, color: 'rgba(145, 204, 117, 0.1)' }]) },
            symbol: 'circle',
            symbolSize: 6
        }]
    });

    fetch('/api/indicators/customerBehavior')
        .then(res => res.json())
        .then(arr => {
            // 按月份分组并计算平均满意度
            const monthMap = new Map();
            arr.forEach(item => {
                const month = item.statistics_month || item.statisticsMonth || '';
                const satisfaction = parseFloat(item.customer_satisfaction || item.customerSatisfaction || 0);
                
                if (!monthMap.has(month)) {
                    monthMap.set(month, { total: 0, count: 0 });
                }
                const data = monthMap.get(month);
                data.total += satisfaction;
                data.count += 1;
            });
            
            const months = Array.from(monthMap.keys()).sort();
            const scores = months.map(m => {
                const data = monthMap.get(m);
                return data.count > 0 ? (data.total / data.count) : 4.5;
            });
            
            chart.setOption({ 
                xAxis: { data: months }, 
                series: [{ data: scores }] 
            });
        })
        .catch(err => console.error('客户满意度数据加载失败:', err));
    return chart;
}

/* ========== 10. 一次性初始化所有图表 & 数据 ========== */
window.addEventListener('DOMContentLoaded', () => {
    initBusinessTypeChart();
    initCityDeliveryChart();
    initCustomerBehaviorChart();
    initPackageStatusChart();
    initTransportEfficiencyChart();
    initWarehouseOperationChart();
    initCustomerSatisfactionChart();
    loadKPI();
    loadOutletTable();

    // 自适应
    window.addEventListener('resize', () => {
        const charts = [
            'businessTypeChart', 'cityDeliveryChart', 'customerBehaviorChart',
            'packageStatusChart', 'transportEfficiencyChart',
            'warehouseOperationChart', 'customerSatisfactionChart'
        ];
        charts.forEach(id => {
            const instance = echarts.getInstanceByDom(document.getElementById(id));
            if (instance) instance.resize();
        });
    });
});